package com.nl.controller.common.util;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.SimpleHttpConnectionManager;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.util.EntityUtils;

/**
 * ���� httpclient  http������
 * @author sj
 *
 */
public class HttpClientUtil {

    private static RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(20000)
            .setConnectionRequestTimeout(20000)
            .setSocketTimeout(20000).build();

    public static final String CHARSET = "UTF-8";
    private static Map<String, String> headers = new HashMap<String, String>();  

    public static String httpPost(String url, Map<String, String> param) throws Exception{  
        //System.out.println("httpPost URL [" + url + "] start ")
        DefaultHttpClient httpclient = null;  
        HttpPost httpPost = null;  
        HttpResponse response = null;  
        HttpEntity entity = null;  
        String result = "";  
        StringBuffer suf = new StringBuffer();  
        try {  
            httpclient = new DefaultHttpClient();  
            // ����cookie�ļ�����---�����Ƿ���Ҫ  
            httpPost = new HttpPost(url);
            // ���ø���ͷ��Ϣ  
            for (Entry<String, String> entry : headers.entrySet()) {  
                httpPost.setHeader(entry.getKey(), entry.getValue());  
            }  
            List<NameValuePair> params = new ArrayList<NameValuePair>();  
            // ������ֲ���  
            if (null != param) {  
                for (Entry<String, String> set : param.entrySet()) {  
                    String key = set.getKey();  
                    String value = set.getValue() == null ? "" : set.getValue().toString();  
                    params.add(new BasicNameValuePair(key, value));  
                    suf.append(" [" + key + "-" + value + "] ");  
                }  
            }  
            StringEntity se = new UrlEncodedFormEntity(params);
    		se.setContentEncoding("UTF-8");
    		se.setContentType("application/json");// ����json��Ҫ����contentType
            httpPost.setEntity(se);  
            //System.out.println("params " + params)
            // �������ӳ�ʱʱ��  
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),20000);  
            // ���ö����ݳ�ʱʱ��  
            HttpConnectionParams.setSoTimeout(httpPost.getParams(),20000);  
            response = httpclient.execute(httpPost);  
            int statusCode = response.getStatusLine().getStatusCode();  
            System.out.println("====statusCode:  [" + statusCode + "]=======");  
            if (statusCode != HttpStatus.SC_OK) {  
          	  //System.out.println("HttpStatus ERROR" + "Method failed: "+ response.getStatusLine())
              return "";  
             } else {  
                entity = response.getEntity();  
                if (null != entity) {  
                    byte[] bytes = EntityUtils.toByteArray(entity);  
                    result = new String(bytes, "UTF-8");  
                } else {  
                	//System.out.println("httpPost URL [" + url+ "],httpEntity is null.")
                }  
                return result;  
           }  
            
        } catch (Exception e) {  
        	//System.out.println("httpPost URL [" + url + "] error, ")
        	throw e;
        } finally {  
            if (null != httpclient) {  
                httpclient.getConnectionManager().shutdown();
            }  
            
            System.out.println("RESULT:  [" + result + "]");  
        }  
    }
    
    public static String postMethod(String url, Map<String, String> map)
			throws Exception {
		HttpClient client = new HttpClient(new HttpClientParams(),
				new SimpleHttpConnectionManager(true));
		PostMethod postMethod = new PostMethod(url);
		postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "utf-8");
		List<org.apache.commons.httpclient.NameValuePair> nameValuePairs = new ArrayList<org.apache.commons.httpclient.NameValuePair>();
		for (Map.Entry<String, String> entry : map.entrySet()) {
			nameValuePairs.add(new org.apache.commons.httpclient.NameValuePair(entry.getKey(), entry.getValue()));
		}
		String response="";
		try {
			org.apache.commons.httpclient.NameValuePair[] requestBody = new org.apache.commons.httpclient.NameValuePair[nameValuePairs.size()];
			nameValuePairs.toArray(requestBody);
			postMethod.setRequestBody(requestBody);
			client.executeMethod(postMethod);
			System.out.println(postMethod.getStatusLine());
			response = postMethod.getResponseBodyAsString();
			System.out.println(response);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			postMethod.releaseConnection();
		}
		return response;
	}
    
	/**
	 * 
	 * desc:
	 * @author sj
	 * @date 2016-5-16 ����10:32:36
	 * @param parameterMap
	 * @return
	 * @throws Exception
	 */
	public static String sendHttpRequest(String url, Map<String,String> parameterMap) throws Exception{
		StringBuffer parameterBuffer = new StringBuffer();
        if (parameterMap != null) {
            Iterator iterator = parameterMap.keySet().iterator();
            String key = null;
            String value = null;
            while (iterator.hasNext()) {
                key = (String)iterator.next();
                if (parameterMap.get(key) != null) {
                    value = (String)parameterMap.get(key);
                } else {
                    value = "";
                }
                
                parameterBuffer.append(key).append("=").append(value);
                if (iterator.hasNext()) {
                    parameterBuffer.append("&");
                }
            }
        }
        System.out.println("POST parameter : " + parameterBuffer.toString().trim().replaceAll("\\+", "%2B").replaceAll("\\n", ""));
        URL localURL = new URL(url);
        HttpURLConnection httpURLConnection = (HttpURLConnection)localURL.openConnection();
        httpURLConnection.setDoOutput(true);
        httpURLConnection.setDoInput(true);
        httpURLConnection.setRequestProperty("Accept-Charset", "utf-8");
        httpURLConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
        httpURLConnection.setRequestProperty("Content-Length", String.valueOf(parameterBuffer.length()));
        httpURLConnection.setRequestMethod("POST"); //�趨����ķ���Ϊ"POST"��Ĭ����GET
        httpURLConnection.setConnectTimeout(20000); //���������ĳ�ʱʱ�䣨��λ�����룩
        httpURLConnection.setReadTimeout(20000); //��������ȡ���ݵĳ�ʱʱ�䣨��λ�����룩
        OutputStream outputStream = null;
        InputStream inputStream = null;
        InputStreamReader inputStreamReader = null;
        BufferedReader reader = null;
        StringBuffer resultBuffer = new StringBuffer();
        String tempLine = null;
		try {
			outputStream = httpURLConnection.getOutputStream();
			outputStream.write(parameterBuffer.toString().trim().replaceAll("\\+", "%2B").replaceAll("\\n", "").getBytes("utf-8"));
            httpURLConnection.connect();
            inputStream = httpURLConnection.getInputStream();
            inputStreamReader = new InputStreamReader(inputStream);
            reader = new BufferedReader(inputStreamReader);
            while ((tempLine = reader.readLine()) != null) {
                resultBuffer.append(tempLine);
            }
            
		} catch (Exception e) {
			throw e;
		}finally {
            if (outputStream != null) {
                outputStream.close();
            }
            if (reader != null) {
                reader.close();
            }
            if (inputStreamReader != null) {
                inputStreamReader.close();
            }
            if (inputStream != null) {
                inputStream.close();
            }
        }
		return resultBuffer.toString();
	}
	
	public static String httpPostForZx(String url, Map<String, String> param) throws Exception{  
        //System.out.println("httpPost URL [" + url + "] start ") 
        DefaultHttpClient httpclient = null;  
        HttpPost httpPost = null;  
        HttpResponse response = null;  
        HttpEntity entity = null;  
        String result = "";  
        StringBuffer suf = new StringBuffer();  
        try {  
            httpclient = new DefaultHttpClient();  
            // ����cookie�ļ�����---�����Ƿ���Ҫ  
            httpPost = new HttpPost(url);
            // ���ø���ͷ��Ϣ  
            for (Entry<String, String> entry : headers.entrySet()) {  
                httpPost.setHeader(entry.getKey(), entry.getValue());  
            }  
            List<NameValuePair> params = new ArrayList<NameValuePair>();  
            // ������ֲ���  
            if (null != param) {  
                for (Entry<String, String> set : param.entrySet()) {  
                    String key = set.getKey();  
                    String value = set.getValue() == null ? "" : set.getValue().toString();  
                    params.add(new BasicNameValuePair(key, value));  
                    suf.append(" [" + key + "-" + value + "] ");  
                }  
            }  
            StringEntity se = new UrlEncodedFormEntity(params);
    		se.setContentEncoding("UTF-8");
    		se.setContentType("application/x-www-form-urlencoded");// ����json��Ҫ����contentType
            httpPost.setEntity(se);  
            // �������ӳ�ʱʱ��  
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),20000);  
            // ���ö����ݳ�ʱʱ��  
            HttpConnectionParams.setSoTimeout(httpPost.getParams(),20000);  
            response = httpclient.execute(httpPost);  
            int statusCode = response.getStatusLine().getStatusCode();  
            System.out.println("====statusCode:  [" + statusCode + "]=======");  
            if (statusCode != HttpStatus.SC_OK) {  
              return "";  
             } else {  
                entity = response.getEntity();  
                if (null != entity) {  
                    byte[] bytes = EntityUtils.toByteArray(entity);  
                    result = new String(bytes, "UTF-8");  
                } 
                return result;  
           }  
            
        } catch (Exception e) {  
        	throw e;
        } finally {  
            if (null != httpclient) {  
                httpclient.getConnectionManager().shutdown();
            }  
            
            System.out.println("RESULT:  [" + result + "]");  
        }  
    }
	
	public static Map<String,String> httpPostWithXml(String url, String reqxml
            ,String charset,Map<String, String> headers){  
        Map<String,String>retMap = new HashMap<String,String>();
        DefaultHttpClient httpclient = null;  
        HttpPost httpPost = null;  
        HttpResponse response = null;  
        HttpEntity entity = null;  
        String retMsg = "";
        String retCode="-1";
        try {  
            httpclient = new DefaultHttpClient();  
            // ����cookie�ļ�����---�����Ƿ���Ҫ  
//          httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,  
//                  CookiePolicy.BROWSER_COMPATIBILITY) 
            httpPost = new HttpPost(url); 
            httpPost.setHeader("Content-Type", "text/xml;charset="+charset);
            // ���ø���ͷ��Ϣ
            if(headers!=null){
                for (Entry<String, String> entry : headers.entrySet()) {  
                    httpPost.setHeader(entry.getKey(), entry.getValue());  
                }  
            }
            StringEntity entityParam = new StringEntity(reqxml,charset);//���������������    
            httpPost.setEntity(entityParam);
            // �������ӳ�ʱʱ��  
            HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),30000);  
            // ���ö����ݳ�ʱʱ��  
            HttpConnectionParams.setSoTimeout(httpclient.getParams(),30000);  
            response = httpclient.execute(httpPost);  
          int statusCode = response.getStatusLine().getStatusCode();  
          if (statusCode != HttpStatus.SC_OK) {  
              retMsg= "HttpStatus ERROR" + " Method failed: "+ response.getStatusLine(); 
              retCode="-2";
          } else {  
            entity = response.getEntity();  
            if (null != entity) { 
                byte[] bytes = EntityUtils.toByteArray(entity); 
                retCode="0";
                retMsg = new String(bytes, charset);  
            } else {  
                retCode="-3";
                retMsg="httpPost URL [" + url+ "],httpEntity is null";
            }  
          }  
        } catch (Exception e) {  
            retCode="-99";
            retMsg="httpPost URL [" + url + "] error: "+e.getMessage();
        } finally {  
            if (null != httpclient) {  
                httpclient.getConnectionManager().shutdown();
            }  
        } 
        retMap.put("retCode", retCode);
        retMap.put("retMsg", retMsg);
        return retMap;
    }
	
	public static Map<String,String> httpPostWithXml(String url, String reqxml
	        ,String reqcharset,String respcharset,Map<String, String> headers){  
	    Map<String,String>retMap = new HashMap<String,String>();
	    DefaultHttpClient httpclient = null;  
	    HttpPost httpPost = null;  
	    HttpResponse response = null;  
	    HttpEntity entity = null;  
	    String retMsg = "";
	    String retCode="-1";
	    try {  
	        httpclient = new DefaultHttpClient();  
	        // ����cookie�ļ�����---�����Ƿ���Ҫ  
//          httpclient.getParams().setParameter(ClientPNames.COOKIE_POLICY,  
//                  CookiePolicy.BROWSER_COMPATIBILITY) 
	        httpPost = new HttpPost(url); 
	        httpPost.setHeader("Content-Type", "text/xml;charset="+reqcharset);
	        // ���ø���ͷ��Ϣ
	        if(headers!=null){
	            for (Entry<String, String> entry : headers.entrySet()) {  
	                httpPost.setHeader(entry.getKey(), entry.getValue());  
	            }  
	        }
	        StringEntity entityParam = new StringEntity(reqxml,reqcharset);//���������������    
	        httpPost.setEntity(entityParam);
	        // �������ӳ�ʱʱ��  
	        HttpConnectionParams.setConnectionTimeout(httpclient.getParams(),30000);  
	        // ���ö����ݳ�ʱʱ��  
	        HttpConnectionParams.setSoTimeout(httpclient.getParams(),30000);  
	        response = httpclient.execute(httpPost);  
	        int statusCode = response.getStatusLine().getStatusCode();  
	        if (statusCode != HttpStatus.SC_OK) {  
	            retMsg= "HttpStatus ERROR" + " Method failed: "+ response.getStatusLine(); 
	            retCode="-2";
	        } else {  
	            entity = response.getEntity();  
	            if (null != entity) { 
	                byte[] bytes = EntityUtils.toByteArray(entity); 
	                retCode="0";
	                retMsg = new String(bytes, respcharset);  
	            } else {  
	                retCode="-3";
	                retMsg="httpPost URL [" + url+ "],httpEntity is null";
	            }  
	        }  
	    } catch (Exception e) {  
	        retCode="-99";
	        retMsg="httpPost URL [" + url + "] error: "+e.getMessage();
	    } finally {  
	        if (null != httpclient) {  
	            httpclient.getConnectionManager().shutdown();
	        }  
	    } 
	    retMap.put("retCode", retCode);
	    retMap.put("retMsg", retMsg);
	    return retMap;
	}

    public static BaseResult<String> sendGet(String url,Map<String, String> querys,String charset,Map<String,String> headers){
        HttpGet httpGet = new HttpGet(buildUrl(url,querys));
        httpGet.setConfig(requestConfig);
        if(headers!=null){
            for (Entry<String, String> entry : headers.entrySet()) {
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }
        }
        return sendGet(httpGet,charset);
    }

    private static BaseResult<String> sendGet(HttpGet httpGet,String charset){
        BaseResult<String> result = BaseResult.newFailInstance();
        CloseableHttpClient httpClient=null;
        CloseableHttpResponse response=null;
        HttpEntity httpEntity=null;
        try {
            httpClient = HttpClients.createDefault();
            response = httpClient.execute(httpGet);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode!=HttpStatus.SC_OK){
                result.setRetCode(String.valueOf(statusCode));
                result.setRetMsg("HTTP ERROR HttpStatus: "+ response.getStatusLine());
            }else{
                httpEntity = response.getEntity();
                if(httpEntity!=null){
                    result.setRetCode("0");
                    result.setData(EntityUtils.toString(httpEntity, charset));
                }else{
                    result.setRetCode(String.valueOf(statusCode));
                    result.setRetMsg("消息内容为空");
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
            result.setRetCode("-99");
            result.setRetMsg(" httpPost error: "+e.getMessage());
        } finally{
            if(response!=null){
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(httpGet!=null && !httpGet.isAborted()){
                httpGet.releaseConnection();
                httpGet.abort();
            }
            if(httpClient!=null){
                try {
                    httpClient.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return result;
    }

    private static String buildUrl(String url, Map<String, String> querys) {
        StringBuilder sbUrl = new StringBuilder();
        if (!StringUtils.isBlank(url)) {
            sbUrl.append(url);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        try {
                            sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                        } catch (UnsupportedEncodingException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }
        return sbUrl.toString();
    }
	
	
}
